// Token key
const TOKEN_KEY = 'dhcc-auth';

export function getToken(): string | null {
  const token = localStorage.getItem(TOKEN_KEY);
  if (token && !token.startsWith('Bearer ')) {
    return `Bearer ${token}`;
  }
  return token;
}

export function setToken(token: string): void {
  const authToken = token.startsWith('Bearer ') ? token : `Bearer ${token}`;
  localStorage.setItem(TOKEN_KEY, authToken);
}

export function removeToken(): void {
  localStorage.removeItem(TOKEN_KEY);
}

export const isAuthenticated = () => {
  return !!getToken();
};

// 检查token是否即将过期
export const checkTokenExpiration = () => {
  const token = getToken();
  if (!token) return true;

  try {
    const payload = JSON.parse(atob(token.split('.')[1]));
    const expirationTime = payload.exp * 1000;
    const currentTime = Date.now();
    // 如果token将在5分钟内过期，返回true
    return (expirationTime - currentTime) < 5 * 60 * 1000;
  } catch (error) {
    return true;
  }
};
